<template>
    <div>
        <van-nav-bar
            title="群通知"
            left-text="返回"
            left-arrow
            @click-left="$router.go(-1)"
        />
        
        <van-empty v-if="groupNotifications.length === 0" description="暂无群通知" />
        
        <van-list
            v-else
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
            <van-cell v-for="notification in groupNotifications" :key="notification._id" class="notification-item">
                <template #title>
                    <div class="notification-header">
                        <van-image :src="notification.groupAvatar || 'https://img.yzcdn.cn/vant/cat.jpeg'" width="40" height="40" round />
                        <div class="notification-info">
                            <div class="notification-title">{{ notification.groupName }}</div>
                            <div class="notification-desc">{{ getNotificationDesc(notification) }}</div>
                        </div>
                    </div>
                </template>
                <template #default>
                    <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
                </template>
                <template #right-icon>
                    <div class="notification-actions" v-if="notification.status === 'pending'">
                        <van-button size="small" type="primary" @click="handleAccept(notification)">接受</van-button>
                        <van-button size="small" @click="handleReject(notification)">拒绝</van-button>
                    </div>
                    <div class="notification-status" v-else>
                        {{ getStatusText(notification.status) }}
                    </div>
                </template>
            </van-cell>
        </van-list>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import socket from '@/socket';

export default {
    name: 'GroupNotificationView',
    data() {
        return {
            groupNotifications: [],
            loading: false,
            finished: true,
            currentPage: 1,
            pageSize: 10
        };
    },
    computed: {
        ...mapState(['user'])
    },
    mounted() {
        this.getGroupNotifications();
        this.setupSocketListeners();
    },
    beforeDestroy() {
        this.removeSocketListeners();
    },
    methods: {
        getGroupNotifications() {
            // 请求获取群通知列表
            socket.emit('get_group_notifications', {
                phone: this.user.phone,
                page: this.currentPage,
                pageSize: this.pageSize
            }, (response) => {
                if (response && response.code === 200) {
                    this.groupNotifications = response.notifications || [];
                    this.finished = this.groupNotifications.length < this.pageSize;
                } else {
                    this.$toast.fail('获取群通知失败');
                }
                this.loading = false;
            });
        },
        
        setupSocketListeners() {
            // 监听新的群通知
            socket.on('newGroupNotification', (notification) => {
                this.groupNotifications.unshift(notification);
            });
            
            // 监听群通知状态变更
            socket.on('groupNotificationUpdated', (updatedNotification) => {
                const index = this.groupNotifications.findIndex(n => n._id === updatedNotification._id);
                if (index !== -1) {
                    this.$set(this.groupNotifications, index, updatedNotification);
                }
            });
        },
        
        removeSocketListeners() {
            socket.off('newGroupNotification');
            socket.off('groupNotificationUpdated');
        },
        
        onLoad() {
            // 加载更多通知
            this.currentPage++;
            this.getGroupNotifications();
        },
        
        handleAccept(notification) {
            socket.emit('handle_group_invitation', {
                notificationId: notification._id,
                phone: this.user.phone,
                action: 'accept'
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('已加入群聊');
                    // 更新通知状态
                    const index = this.groupNotifications.findIndex(n => n._id === notification._id);
                    if (index !== -1) {
                        this.$set(this.groupNotifications[index], 'status', 'accepted');
                    }
                } else {
                    this.$toast.fail(response?.message || '操作失败');
                }
            });
        },
        
        handleReject(notification) {
            socket.emit('handle_group_invitation', {
                notificationId: notification._id,
                phone: this.user.phone,
                action: 'reject'
            }, (response) => {
                if (response && response.code === 200) {
                    this.$toast.success('已拒绝邀请');
                    // 更新通知状态
                    const index = this.groupNotifications.findIndex(n => n._id === notification._id);
                    if (index !== -1) {
                        this.$set(this.groupNotifications[index], 'status', 'rejected');
                    }
                } else {
                    this.$toast.fail(response?.message || '操作失败');
                }
            });
        },
        
        getNotificationDesc(notification) {
            switch(notification.type) {
                case 'invitation':
                    return `${notification.inviterName}邀请你加入群聊`;
                case 'system':
                    return notification.content;
                default:
                    return '新群通知';
            }
        },
        
        getStatusText(status) {
            const statusMap = {
                'pending': '待处理',
                'accepted': '已接受',
                'rejected': '已拒绝',
                'expired': '已过期'
            };
            return statusMap[status] || '未知状态';
        },
        
        formatTime(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            
            // 简单日期格式化
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            // 判断是否是今天
            const today = new Date();
            if (today.toDateString() === date.toDateString()) {
                return `今天 ${hours}:${minutes}`;
            }
            
            // 判断是否是昨天
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            if (yesterday.toDateString() === date.toDateString()) {
                return `昨天 ${hours}:${minutes}`;
            }
            
            // 其他日期显示完整日期
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
    }
};
</script>

<style lang="less" scoped>
.notification-item {
    margin-bottom: 8px;
    
    .notification-header {
        display: flex;
        align-items: center;
        
        .notification-info {
            margin-left: 10px;
            
            .notification-title {
                font-size: 16px;
                font-weight: 500;
            }
            
            .notification-desc {
                font-size: 14px;
                color: #999;
                margin-top: 4px;
            }
        }
    }
    
    .notification-time {
        font-size: 12px;
        color: #999;
    }
    
    .notification-actions {
        display: flex;
        justify-content: space-between;
        width: 120px;
        
        .van-button {
            margin-left: 8px;
            
            &:first-child {
                margin-left: 0;
            }
        }
    }
    
    .notification-status {
        font-size: 14px;
        color: #999;
    }
}
</style>